<template>
  <t-dialog :visible="visible" width="40%" @confirm="submitForm" @close="close">
    <t-form ref="formRef" :rules="FORM_RULES" :data="formData" colon>
      <t-row :gutter="[16, 16]" style="margin-left: 0px;margin-right: 0px;">
        <t-col :span="6">
          <t-form-item label="姓名" name="name">
            <t-input v-model="formData.name" placeholder="请输入内容" @enter="onEnter"></t-input>
          </t-form-item>
        </t-col>
        <t-col :span="6">
          <t-form-item label="手机号码" name="tel">
            <t-input v-model="formData.tel" placeholder="请输入内容" @enter="onEnter"></t-input>
          </t-form-item>
        </t-col>

        <t-col :span="6">
          <t-form-item label="接收短信" name="status">
            <t-switch v-model="formData.status"></t-switch>
          </t-form-item>
        </t-col>

      </t-row>
    </t-form>
  </t-dialog>

</template>

<script setup lang="ts">
import { Data, FormInstanceFunctions, FormRules, InputProps } from 'tdesign-vue-next';
import { PropType } from 'vue';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  userInfo: {
    type: Object as PropType<{
      name: string;
      tel: string;
      status: boolean;
      gender: string;
    }>,
    default: () => ({
      name: '',
      tel: '',
      status: false,
      gender: ''
    })
  }
})

const emits = defineEmits(['update:visible'])

const formData = ref({
  name: '',
  tel: '',
  status: false,
  gender: ''
});

onMounted(() => {
  formData.value = props.userInfo;
})

const FORM_RULES: FormRules<Data> = {
  name: [{ required: true, message: '姓名必填' }]
};

// 表单校验
const formRef = ref<FormInstanceFunctions>();
const submitForm = () => {
  formRef.value?.validate().then((validateResult) => {
    console.log('校验通过', validateResult);
    if (validateResult === true) {
      console.log('校验通过');

      close();
    }
  });

};

// 禁用 Input 组件，按下 Enter 键时，触发 submit 事件
const onEnter: InputProps['onEnter'] = (_, { e }) => {
  e.preventDefault();
};

const close = () => {
  emits('update:visible', false);
  formRef.value?.reset();
}
</script>

<style lang="less" scoped></style>
